package com.test.socket;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TimelimitEchoProtocol implements Runnable {
	private static final int BUFSIZE = 32; // size (bytes) of buffer
	private static final String TIMELIMIT = "10000";// default limits
	private static final String TIMELIMITPROP = "Timelimit"; // property

	private static int timelimit;
	private Socket clntSock;
	private Logger logger;

	public TimelimitEchoProtocol(Socket clntSock, Logger logger) {
		this.clntSock = clntSock;
		this.logger = logger;
		// get the time limit from the system properties or take the default
		timelimit = Integer.parseInt(System.getProperty(TIMELIMITPROP,
				TIMELIMIT));
	}

	public static void handleEchoClient(Socket clntSock, Logger logger) {
		try {
			// get the input an output i/o streams from socket
			InputStream in = clntSock.getInputStream();
			OutputStream out = clntSock.getOutputStream();
			int recvMsgSize; // size of received message
			int totalBytesEchoed = 0; // bytes received from client
			byte[] echoBuffer = new byte[BUFSIZE]; // received buffer
			long endTime = System.currentTimeMillis() + timelimit;
			int timeBoundMillis = timelimit;
			clntSock.setSoTimeout(timeBoundMillis);
			// receive until client closes connection , indicated by -1
			while ((timeBoundMillis > 0)
					&& ((recvMsgSize = in.read(echoBuffer)) != -1)) {
				out.write(echoBuffer, 0, recvMsgSize);
				totalBytesEchoed += recvMsgSize;
				timeBoundMillis = (int) (endTime - System.currentTimeMillis());
				clntSock.setSoTimeout(timeBoundMillis);
			}
			logger.info("Client " + clntSock.getRemoteSocketAddress()
					+ ", echoed " + totalBytesEchoed + " bytes. ");

		} catch (Exception e) {
			logger.log(Level.WARNING,"Exception in echo protocol",e);
		}
	}

	@Override
	public void run() {
		handleEchoClient(clntSock, logger);

	}

}
